package com.haiwei.poi.word.loop;

import com.haiwei.poi.common.exception.HaiweiGeneralException;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.util.List;
import java.util.Stack;

/**
 * HaiweiTable 工具类.
 *
 * @date: 2022-06-27
 * @version: 1.0
 * @author: karry@haiwei.com
 */
public class HaiweiTableUtil {
    
    /**
     * 获取HaiweiTable
     * @param xwpfTable
     * @return
     */
    public static HaiweiTable getHaiweiTable(XWPFTable xwpfTable) {
        List<XWPFTableRow> xwpfTableRows = xwpfTable.getRows();
        
        Stack<HaiweiRowGroup> stack = new Stack<>();
        // 初始化root
        HaiweiTable HaiweiTable = new HaiweiTable(xwpfTable,0,xwpfTableRows.size()-1);
        stack.push(HaiweiTable);
        
        for(int i  = 0 ; i < xwpfTableRows.size() ; i++){
            XWPFTableRow row = xwpfTableRows.get(i);
            HaiweiRowGroup rowGroup = null;
            if(!stack.empty()){
                rowGroup = stack.peek();
            }
            List<XWPFTableCell> cells = row.getTableCells();
            // 如果是1，并且是loop开始
            if(cells.size() == 1){
                String text = row.getTableCells().get(0).getText();
                if(HaiweiLoopSginParser.isLoopStartSign(text)) {
                    HaiweiLoopSign loopSign = HaiweiLoopSginParser.parse(text);
                    if(loopSign != null && rowGroup != null){
                        HaiweiRowGroupLoop loop = new HaiweiRowGroupLoop(xwpfTable,i,loopSign);
                        stack.push(loop);
                        rowGroup.addRowGroup(loop);
                    }
                }else if(HaiweiLoopSginParser.isLoopEndSign(text)){
                    // 如果是1，并且是loop结尾,需要挨个处理了
                    HaiweiRowGroup tempRowGrop = stack.pop();
                    if(tempRowGrop == null || !(tempRowGrop instanceof HaiweiRowGroupLoop)){
                        throw new HaiweiGeneralException("loop begin and end flag mismatch");
                    }
                    HaiweiRowGroupLoop loop = (HaiweiRowGroupLoop) tempRowGrop;
                    loop.setEndIndex(i);
                }else if(rowGroup != null){
                    rowGroup.addRowGroup(new HaiweiRowGroupBasic(xwpfTable,i,i));
                }
            }else if(rowGroup != null){
                rowGroup.addRowGroup(new HaiweiRowGroupBasic(xwpfTable,i,i));
            }
        }
        return HaiweiTable;
    }
}
